import { IWriteFile } from '@/types';
import fs from 'fs';

const getCatalogue = (path: string) => {
    if (fs.existsSync(path)) return fs.readdirSync(path);
    else return [];
};

const isFile = (filePath) => {
    try {
        return fs.statSync(filePath).isFile()
    } catch {
        return null;
    }
};

const isDir = (filePath) => {
    try {
        return fs.statSync(filePath).isDirectory()
    } catch {
        return null;
    }
};

const removeFile = (filePath) => {
    if (isFile(filePath)) {
        fs.unlinkSync(filePath);
    }
    
    else if (isDir(filePath)) {
        // 递归删除所有文件夹下文件
        const list = fs.readdirSync(filePath);
        list.forEach((docName) => {
            removeFile(`${filePath}/${docName}`);
        });
        fs.rmdirSync(filePath);
    }
}

const writeFile: IWriteFile = (fileName, content, reg?: (RegExp | string)[]) => {
    let origin;

    if (typeof content === 'string') {
        origin = content;
    } else if (Array.isArray(content)) {
        origin = fs.readFileSync(fileName).toString('utf-8');
    } else origin = {...(JSON.parse(fs.readFileSync(fileName).toString('utf-8')) || {}), ...content};

    if (reg) {
        origin = reg.reduce((prev, cur, index) => {
            return content[index].reduce((_p, _c) => {
                return _p.replace(cur, (_$1, $2) => {
                    if (_$1.length !== $2.length) return _$1.replace($2, _c);
                    else return $2 + _c;
                  })
            }, prev);
        }, origin)
    }
    fs.writeFileSync(fileName, typeof origin === 'object' ? JSON.stringify(origin, null, 4) : origin);
};

export {
    getCatalogue,
    isFile,
    isDir,
    removeFile,
    writeFile,
}